package com.common.mvp;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.Nullable;

import com.common.UIApplication;
import com.common.dagger.component.DaggerFragmentComponent;
import com.common.dagger.component.FragmentComponent;
import com.common.dagger.component.MyAppComponent;
import com.util_code.BuildConfig;
import com.util_code.base.mvp.MvpFragment;
import com.util_code.base.mvp.MvpPresenter;
import com.util_code.base.mvp.MvpView;
import com.util_code.dagger.module.FragmentModule;

import butterknife.ButterKnife;
import butterknife.Unbinder;

public abstract class BaseMvpFragment<V extends MvpView, P extends MvpPresenter<V>> extends MvpFragment<V, P> {

    protected Unbinder mUnbinder;

    private FragmentComponent mFragmentComponent;

    /**
     * Creates a new presenter instance,This method will be
     * called from {@link #onViewCreated(View, Bundle)}
     */
    public P createPresenter() {
        setupComponent(UIApplication.getMyAppComponent());
        initInject();
        return presenter;
    }

    protected void setupComponent(MyAppComponent applicationComponent) {
        mFragmentComponent = DaggerFragmentComponent.builder()
                .myAppComponent(applicationComponent)
                .fragmentModule(getFragmentModule())
                .build();
    }

    protected FragmentModule getFragmentModule() {
        return new FragmentModule(this);
    }

    public FragmentComponent getFragmentComponent() {
        return mFragmentComponent;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(getLayoutId(), null);
        mUnbinder = ButterKnife.bind(this, view);
        return view;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        setup(savedInstanceState, view);
    }

    private void setup(Bundle savedInstanceState, View rootView) {
        setupView(rootView);
        setupData(savedInstanceState);
    }

    protected abstract int getLayoutId();

    protected abstract void initInject();

    protected abstract void setupView(View rootView);

    protected abstract void setupData(Bundle savedInstanceState);

    @Override
    public void onDestroy() {
        super.onDestroy();
        mUnbinder.unbind();
        if (BuildConfig.DEBUG) {
            // use the RefWatcher to watch for fragment leaks:
            UIApplication.getRefWatcher(getActivity()).watch(this);
        }
    }

}
